<?php
namespace app\search\admin;
use app\common\controller\AdminBase;
use app\search\model\Keyword AS Model;
use app\common\traits\AddEditList;
use think\Db;
use think\Validate;
class Content extends AdminBase{
	use AddEditList;
	protected $model;
	protected $form_items=[];
	protected $list_items;
	protected $tab_ext;
	protected $fids;
	protected function _initialize(){
		parent::_initialize();
		$this->model=new Model();
		$this->fids=$this->webdb['search_fid'];
		$this->form_items=[
			['text','keyword','关键词'],
			['text','searchnums','搜索次数'],
			['select','fid','所属栏目','',$this->fids],
			['radio','type','是否显示','关闭后前台不显示这个词',['不显示','显示'],0],
		];
	}
	/**
	 * tags 首页
	 * @return mixed|string
	 */
	public function index(){
		$this->tab_ext=['page_title'=>'热搜管理',];
		$this->list_items=[
			['keyword','关键词名称','text.edit'],
			['searchnums','搜索次数','text.edit'],
			['fid','栏目','select',$this->fids],
			['type','显示状态','select',['不显示','显示']],
		];
		$this->tab_ext['top_button']=[
			['type'=>'add'],
			['type'=>'delete'],
			['url'=>auto_url('qingchu'),'title'=>'清空关键词(清空后需要重新添加)','class'=>' alert']
		];
		$data=$this->model->order('searchnums','desc')->paginate(20);
		return $this->getAdminTable($data);
	}
	/**
	 * 添加
	 * @return mixed|string
	 */
	public function add(){
		$this->tab_ext=['page_title'=>'添加热搜词',];
		if($this->request->isPost()){
			$data=$this->request->post();
			$rule=[
				['keyword','require','请输入关键词'],
			];
			$validate=new Validate($rule);
			$result=$validate->check($data);
			if(!$result){
				$this->error($validate->getError());
			}
			$keyword=Db::name('search_keyword')->where('keyword',$data['keyword'])->find();
			if($keyword){
				$this->error('关键词已经存在');
			}
			if($this->model->create($data)){
				$this->success('保存成功',auto_url('index'));
			}else{
				$this->error('保存失败');
			}
		}
		return $this->addContent();
	}
	/**
	 * 修改
	 * @param null $id
	 * @return mixed|string
	 */
	public function edit($id=null){
		$this->tab_ext=['page_title'=>'修改热搜词',];
		if(empty($id)){
			$this->error('缺少参数');
		}
		$info=$this->getInfoData($id);
		return $this->editContent($info,auto_url('index'));
	}
	/**
	 * 删除
	 * @param $ids
	 */
	public function delete($ids){
		if(empty($ids)){
			$this->error('ID有误');
		}
		$ids=is_array($ids)?$ids:[$ids];
		if($this->model->destroy($ids)){
			$this->success('删除成功','index');
		}else{
			$this->error('删除失败');
		}
	}
	/**
	 * 清空数据表
	 */
	public function qingchu(){
		into_sql("TRUNCATE TABLE qb_search_keyword;",true,0);
		$this->success('清空表成功','index');
	}
}
